#include<iostream>
#include"Socket.hpp"
#include"TcpServer.hpp"
#include"HttpProtocol.hpp"
#include<memory>

//HTML表单工具：https://www.runoob.com/html/html-forms.html

std::string GetSuffix(std::string& suffix)
{
    if(suffix==".html"||suffix=="./htm")return "text/html";
    else if(suffix==".png")return "image/png";
    else if(suffix==".jpg")return "image/jpg";
    else return "text/html";
}

std::string CodetoDesc(int code)
{
    switch (code)
    {
    case 200:
        return "OK";
    case 301:
        return "Moved Permanently";
    case 307:
        return "Temporary Redirect";
    case 403:
        return "Forbidden";
    case 404:
        return "Not Found";
    case 500:
        return "Internal Server Error";
    default:
        return "Unknown";
    }
} 

std::string HandlerHttpRequest(std::string& httprequest)
{
    //收到请求进行反序列化
    HttpRequest req;
    req.Deserialize(httprequest);
    req.Parse();
    //进行打印查看看结果
    req.Dubug();
    int code=200;
    //http底层用的tcp
    std::string content=req.GetFileContent();
    if(content.empty())
    {
        code=404;
        content=req.Get404();
    }
    code=303;
    HttpResponse resp;
    resp.SetCode(code);
    resp.SetCodeDesc(CodetoDesc(code));
    if(!content.empty())
    {
        resp.MakeStatueLine();
        std::string httpheader = "Content-Length: " + std::to_string(content.size()) + "\r\n";
        resp.AddHeader(httpheader);
        std::string httptype = "Content-Type: " + GetSuffix(req.GetSuffix()) + "\r\n";
        resp.AddHeader(httptype);
        //std::string Location="Location: https://www.qq.com/\r\n";
        //resp.AddHeader(Location);
        resp.AddContent(content);
        return resp.Serialize();
    }
    return "";
}


int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        std::cout<<"Usage : "<<argv[0]<<" localport "<<std::endl;
        return 0;
    }
    uint16_t localport=std::stoi(argv[1]);
    std::unique_ptr<TcpServer> tsvr(new TcpServer(localport,HandlerHttpRequest));
    tsvr->Loop();
    return 0;
}